package cc.ls51.api.utils;

import cc.ls51.exception.BusinessException;
import cn.hutool.core.util.StrUtil;
import io.jsonwebtoken.*;
import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;

public class JwtUtil {
    /**
     * JWT 生成密钥使用的密码
     */
    private static final String JWT_RULE = "k32,ld";

    /**
     * JWT 添加至HTTP HEAD中的前缀
     */
    private static final String JWT_SEPARATOR = "Bearer ";
    /**
     * 签发JWT
     * @param id
     * @param userType 可以是JSON数据 尽可能少
     * @param ttlMillis
     * @return  String
     *
     */
    public static String createJWT(String id, String userType, long ttlMillis) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        SecretKey secretKey = generalKey();
        JwtBuilder builder = Jwts.builder()
                .setId(id)
                .setSubject(userType)   // 主题
                .setIssuer("ls51")     // 签发者
                .setIssuedAt(now)      // 签发时间
                .signWith(signatureAlgorithm, secretKey); // 签名算法以及密匙
        if (ttlMillis >= 0) {
            long expMillis = nowMillis + ttlMillis;
            Date expDate = new Date(expMillis);
            builder.setExpiration(expDate); // 过期时间
        }
        return builder.compact();
    }
    /**
     * 校验JWT
     *
     * @param token jwt 内容文本
     * @return ture or false
     */
    public static Boolean checkJWT(String token) {
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(token)!=null;
    }

    private static SecretKey generalKey() {
        byte[] encodedKey;
        encodedKey = Base64.decodeBase64(JWT_RULE);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }

    /**
     *
     * 解析JWT字符串
     * @param jwt
     * @return
     * @throws Exception
     */
    public static Claims parseJWT(String jwt) {
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }
    // 获取用户身份
    public static String getUid(String token) {

        return parseJWT(token).getId();
    }

    /**
     * 获取用户角色
     * @return RoleConstant
     */
    public static String getUserRole(String token) throws BusinessException {
        String userType = parseJWT(token).getSubject();
        if(StrUtil.isEmpty(userType)){
            throw new BusinessException("用户token角色为空");
        }
        return userType;
    }
}
